<template>
  <div id="ymDatePicker">
    <van-popup v-model="show" position="bottom" :close-on-click-overlay="false">
      <van-picker :loading="loading" show-toolbar title="选择地区" @cancel="onPickerCancel" @confirm="onPickerConfirm" :columns="columns" @change="onChange" />
    </van-popup>
  </div>
</template>
<script>
export default {
  props: {
    show: {
      type: Boolean,
      value: true
    }
  },
  created() {
    let columns = [{
      values: [],
      className: "column1"
    }, {
      values: [],
      className: "column2",
    }, {
      values: [],
      className: "column3",
    }]
    this.$http('/api/common/area').then(data => {
      this.area = data
      this.setColumns()
      this.loading = false
    })
  },
  data() {
    return {
      area: [],
      columns: [],
      loading: true
    }
  },
  methods: {
    onPickerCancel() {
      this.$emit('onCancel')
    },
    onPickerConfirm(value, index) {                       
      this.$emit('onConfirm', Array.from(value, x => ({id: x.id, name: x.text})))
    },
    setColumns() {
      let columns = [{
        values: [],
        className: "column1"
      }, {
        values: [],
        className: "column2",
      }, {
        values: [],
        className: "column3",
      }]
      columns[0].values = this.setColumns0()
      columns[1].values = this.setColumns1(0)
      columns[2].values = this.setColumns2(0, 0)
      
      this.columns = columns
    },
    setColumns0() {
      let columns = []
      this.area.map((item, index) => {
        columns.push({
          index,
          id: item.id,
          code: item.code,
          text: item.name
        })
      })
      return columns
    },
    setColumns1(index) {
      let columns = []
      this.area[index].child.map((item, index) => {
        columns.push({
          index,
          id: item.id,
          code: item.code,
          text: item.name
        })
      })
      return columns
    },
    setColumns2(index, idx) {
      let columns = []
      this.area[index].child[idx].child.map((item, index) => {
        columns.push({
          index,
          id: item.id,
          code: item.code,
          text: item.name
        })
      })
      return columns
    },
    onChange(picker, values, index) {
      console.log(values)
      let columns1 = []
      let columns2 = []
      if (index === 0) {
        columns1 = this.setColumns1(values[0].index)
        columns2 = this.setColumns2(values[0].index, 0)
        picker.setColumnValues(1, columns1)
        picker.setColumnValues(2, columns2)
      } else if (index === 1){
        columns2 = this.setColumns2(values[0].index, values[1].index)
        picker.setColumnValues(2, columns2)
      }
    },
  }
}
</script>
